package com.hluobo.library.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.json.JSONObject;

public class StreamTool {

	/**
	 * 流读取工具，从输入流读取数据到字节数组
	 * @param inStream 输入流
	 * @return 字节数组
	 * @throws Throwable
	 */
	public static byte[] readInputStream(InputStream inStream) throws Throwable{
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while(-1 != (len = inStream.read(buffer))){
			outStream.write(buffer, 0, len);
		}
		return outStream.toByteArray();
	}
	
	/**
	 * 从客户端请求输入流中读取json对象
	 * @return JSONObject
	 * @throws Throwable
	 */
	public static JSONObject readRequstString() throws Throwable{
		HttpServletRequest req = ServletActionContext.getRequest();
        InputStream is = req.getInputStream();
        byte[] data = readInputStream(is);
        String jsonStr = new String(data, "UTF-8");
        return new JSONObject(jsonStr);
	}
	
}
